import Vue from 'vue'
import {imagedomain} from '../api/api.js'
const util = {};
//时间转换工具
util.changeDate = function (value) {
    var time = value * 1000;
    var month = new Date(time).getMonth() + 1;
    var date = new Date(time).getDate();
    return month + '月' + date + '日';
}
util.getDate = function (value) {
    var time = value * 1000;
    var now = new Date().getTime();
    var res = (now - time) / 1000 / 86400;
    var month = new Date(time).getMonth() + 1;
    var date = new Date(time).getDate();
    var hour = new Date(time).getHours();
    var min = new Date(time).getMinutes();
    var weekType = new Array("日", "一", "二", "三", "四", "五", "六");
    var week = '星期' + weekType[new Date(time).getDay()];
    if (min < 10) {
        min = '0' + min
    }
    if (new Date().getDate() - new Date(time).getDate() === 0) {
        if (hour > 12) {
            return '下午 ' + (hour - 12) + ':' + min;
        } else {
            return '上午 ' + hour + ':' + min;
        }

    } else if (new Date().getDate() - new Date(time).getDate() === 1) {
        if (hour > 12) {
            return '昨天 ' + ' 下午 ' + (hour - 12) + ':' + min;
        } else {
            return '昨天 ' + ' 上午 ' + hour + ':' + min;
        }
    }
    else if (new Date().getTime()<new Date(time).getTime()&&new Date().getDate() - new Date(time).getDate() < 7 && new Date().getDay() - new Date(time).getDay() > 0) {
        if (hour > 12) {
            return week + ' 下午 ' + (hour - 12) + ':' + min;
        } else {
            return week + ' 上午 ' + hour + ':' + min;
        }
    } else {
        if (hour > 12) {
            return month + '月' + date + '日' + ' 下午 ' + (hour - 12) + ':' + min;
        } else {
            return month + '月' + date + '日' + ' 上午 ' + hour + ':' + min;
        }

    }
}
//浏览器判断
util.browser = {
    versions: function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {         //移动终端浏览器版本信息
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
            weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
            qq: !!u.match(/QQ\/([\d\.]+)/gi)
        };
    }(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
};
//h5调用native方法
util.JsBridge = function (funName, params, callback,noJSON,noTry) {
    "use strict";
    function bridgeFuc() {
        let bridge = window.WebViewJavascriptBridge;
        if (Object.prototype.toString.call(params) !== '[object Object]') return;
        params = encodeURI(JSON.stringify(params));
        bridge.callHandler(funName, params, (res) => {
            if (Object.prototype.toString.call(res) === '[object String]'&& !noJSON) {
                res = JSON.parse(res);
            }
            callback(res)
        });
    }

    if (!noTry) {
        try {
            bridgeFuc();
        } catch (e) {
            console.log(e)
        }
    } else {
        bridgeFuc();
    }
}
//native调用h5方法
util.jsBridgeCallBack = function (funName, callback) {
    window[funName] = function (res) {
        if (callback) {
            callback(res);
        }
    }
}
//获取access_token
util.getToken = function () {
    return new Promise(function (resolve, reject) {
        try {
            util.JsBridge('getUserInfo', {}, (res) => {
                sessionStorage.setItem('access_token', res.accessToken || res.access_token);
                sessionStorage.setItem('token_type', 'bearer');
                resolve()
            },false,true);
        } catch (e) {
            reject();
        }
    })
}
//打点
util.sendLog = function (type,appType,content) {
    util.JsBridge('writeH5Log', {
        type:type,
        appType:appType,
        content:content
    }, (res) => {});
}
//获取默认头像路径
util.getDefaultHeader = function (id) {
    return imagedomain + '/photo/user_header' + (id-1) % 10 + '.png';
}
//获取高斯模糊背景
util.getDefaultBg = function () {
    return imagedomain + 'photo/bg' + Math.floor(Math.random() * 3) + '.png?imageMogr2/blur/40x40/imageView2/0/w/750/format/jpeg';
}
//页面跳转中转处理
util.pageMiddleWare = function (url) {
    // window.location.href.indexOf('jlb_pageMiddleWare')!==-1?window.location.href=url:
    util.JsBridge('createWebView', {url: url}, (res) => {
    });
}
//表情转换编码
util.utf16toEntities = function (str) {
    var patt = /[\ud800-\udbff][\udc00-\udfff]/g;
    // 检测utf16字符正则
    str = str.replace(patt, function (char) {
        var H, L, code;
        if (char.length === 2) {
            H = char.charCodeAt(0);
            // 取出高位
            L = char.charCodeAt(1);
            // 取出低位
            code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00;
            // 转换算法
            return "&#" + code + ";";
        } else {
            return char;
        }
    });
    return str;
};
//表情转换解码
util.entitiestoUtf16 = function (str) {
    // 检测出形如&#12345;形式的字符串
    var strObj = util.utf16toEntities(str);
    var patt = /&#\d+;/g;
    var H, L, code;
    var arr = strObj.match(patt) || [];
    for (var i = 0; i < arr.length; i++) {
        code = arr[i];
        code = code.replace('&#', '').replace(';', '');
        // 高位
        H = Math.floor((code - 0x10000) / 0x400) + 0xD800;
        // 低位
        L = (code - 0x10000) % 0x400 + 0xDC00;
        code = "&#" + code + ";";
        var s = String.fromCharCode(H, L);
        strObj=strObj.replace(code, s);
    }
    return strObj;
};
util.goBack=function(){
    util.JsBridge('refreshAppCellInfo',{},()=>{})
    history.go(-1);
}
util.autoTextarea = function (elem, extra, maxHeight) {
    extra = extra || 0;
    var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
        isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
        addEvent = function (type, callback) {
            elem.addEventListener ?
                elem.addEventListener(type, callback, false) :
                elem.attachEvent('on' + type, callback);
        },
        getStyle = elem.currentStyle ? function (name) {
            var val = elem.currentStyle[name];

            if (name === 'height' && val.search(/px/i) !== 1) {
                var rect = elem.getBoundingClientRect();
                return rect.bottom - rect.top -
                    parseFloat(getStyle('paddingTop')) -
                    parseFloat(getStyle('paddingBottom')) + 'px';
            }
            ;

            return val;
        } : function (name) {
            return getComputedStyle(elem, null)[name];
        },
        minHeight = parseFloat(getStyle('height'));

    elem.style.resize = 'none';

    var change = function () {
        var scrollTop, height,
            padding = 0,
            style = elem.style;

        if (elem._length === elem.value.length) return;
        elem._length = elem.value.length;

        if (!isFirefox && !isOpera) {
            padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
        }
        ;
        scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

        elem.style.height = minHeight + 'px';
        if (elem.scrollHeight > minHeight) {
            if (maxHeight && elem.scrollHeight > maxHeight) {
                height = maxHeight - padding;
                style.overflowY = 'auto';
            } else {
                height = elem.scrollHeight - padding;
                style.overflowY = 'hidden';
            };
            style.height = height + extra + 'px';
            scrollTop += parseInt(style.height) - elem.currHeight;
            document.body.scrollTop = scrollTop;
            document.documentElement.scrollTop = scrollTop;
            elem.currHeight = parseInt(style.height);
        };
    };

    addEvent('propertychange', change);
    addEvent('input', change);
    addEvent('focus', change);
    change();
};
util.audio = document.createElement('audio');
document.body.appendChild(util.audio);
Vue.prototype.$util = util;
Vue.prototype.$clearAudioId = '';
/*
 * @description: 日期格式化
 *
 * @update: lwq (2017-03-06)
 */
Date.prototype.Format = function (format) {
    var o = {
        "y+": this.getFullYear(),
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
    };
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};
/*
 * @description: 倒计时格式化
 *
 * @update: lwq (2017-03-06)
 */
Date.prototype.Time = function (format) {
    var o = {
        "d+": this.getUTCDate() - 1,
        "h+": this.getUTCHours(),
        "m+": this.getUTCMinutes(),
        "s+": this.getUTCSeconds(),
    };
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};
